package com.foreknow.service.impl;

import com.foreknow.bean.User;
import com.foreknow.dao.UserDao;
import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.UserService;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 业务层(需要处理事务)
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public int addUser(User user) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        int a = 0;
        try {
            a = userDao.add(user);
            //提交
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            //回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
//        try{
//            userDao.add(user);
//            //提交
//        }catch (){
//            //回滚
//        }
        return a;
    }

    @Override
    public User isValidate(String adminName, String password) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        try {
            return userDao.login(adminName,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        UserService ser = new UserServiceImpl();
        User user = new User();
//        user.setAdminName("ceshi");
//        user.setPassword("134");
//        int b = ser.addUser(user);
//        System.out.println(b);
        user = ser.isValidate("tony","124");
        if (user==null){
            System.out.println("shibai");
        }else {
            System.out.println(user.getAdminName()+"welcome");
        }
    }
}
